<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\facade\Session;
use app\admin\validate\Login as ValidateLogin;
use app\admin\model\Admin as ModelAdmin;
use app\Request;
use app\admin\middleware\Auth;

class Login
{
	/**
	 * 权限验证
	 */
	protected $middleware = [
		Auth::class=>['only'=>'index'],
	];

	/**
	 * 构造方法
	 */
	public function __construct(){
	}
	
	/**
	 * 登录
	 */
	public function index(Request $request){
		# 登录请求
		if('POST' == $request->method()){
			$data = $request->param();
			#$validate = validate(ValidateLogin::class)->check($data); # 表单验证
			$validate = new ValidateLogin();
			$result = $validate->check($data);
			if(!$result){
				return json([
					'status' => 2,
					'notice' => $validate->getError(),
					'token' => token(),
				]);
			} else {
				$model = new ModelAdmin(); # 模型处理
				$revalue = $model->login($data);
				if(1 == $revalue['status']){ # login success
					Session::set('administrator',$revalue['value']);
					return json([
						'status'=>1,
						'notice'=>'登录成功！',
					]);
				} else {
					return json(
						[
							'status'=>2,
							'notice'=>$revalue['notice'],
							'token' =>token()
						]
					);
				}
			}
		}
		return view('index');
	}
	
	/**
	 * 退出
	 */
	public function out(){
		Session::delete('administrator');
		return redirect((string)url('admin/login/index'));
	}

}
